var server = "http://11.16.127.24:8219/";


// var coordinatesData = [];
// $.ajax({
//     type: 'get',
//     dataType: "json",
//     data: {
//         httpurl: "cloudSearch/search/basic?table=bayonet&page_size=8855&data_type=3"
//     },
//     url: "http://192.168.1.197:5013/VIAS/web/snapshot/baidu/BayonetMarking",
//     success: function (data) {
//         console.log(data.data.list);
//         $.each(data.data.list, function (i, row) {
//             var geoCoord = row.shape.coordinates;
//             coordinatesData.push({
//                 geometry: {
//                     type: 'Point',
//                     coordinates: geoCoord
//                 },
//                 // count: 10 *( Math.random()*10+1)
//             });
//         });

//         var options = {
//             // fillStyle: 'blue', // 非聚合点的颜色
//             size: 3, // 数值最大值范围
//             maxSize: 20, // 显示的圆最大半径大小
//             minSize: 5, // 显示的圆最大半径大小
//             draw: 'cluster',
//             fillStyle: 'rgba(200, 200, 50, 1)', // 填充颜色
//             strokeStyle: 'rgba(0, 0, 255, 1)', // 描边颜色
//             lineWidth: 2, // 描边宽度
//             globalAlpha: 0.8, // 透明度
//             clusterRadius: 1000, // 聚合像素半径
//             maxZoom: 19, // 最大显示级别
//             unit: 'px',
//             label: { // 网格中显示累加的值总和
//                 show: true,
//                 fillStyle: 'white',
//             },
//             gradient: { 0.25: "rgb(0,0,255)", 0.55: "rgb(0,255,0)", 0.85: "yellow", 1.0: "rgb(255,0,0)" },
//             methods: {
//                 click: function (item) {
//                     console.log(item)
//                 }
//             },
//             // draw: 'simple'
//         }
//         var dataSet = new mapv.DataSet(coordinatesData);
//         var mapvLayer = new mapv.baiduMapLayer(map, dataSet, options);
//         //     var markers =new Array();
//         //     var opts = {
//         //             width : 200,     // 信息窗口宽度
//         //              height: 50,     // 信息窗口高度
//         //             }
//         //     $.each(data.data.list,function(i,row){
//         //         var lon="";
//         //          var lat="";
//         //         lon=row.shape.coordinates[0];
//         //         lat=row.shape.coordinates[1];
//         //         markers[i]=new BMap.Marker(new BMap.Point(lon,lat));
//         //         var infoWindow = new BMap.InfoWindow(row.devName, opts);  // 创建信息窗口对象 
//         //         markers[i].addEventListener("mouseover", function(){          
//         //          map.openInfoWindow(infoWindow,new BMap.Point(lon,lat)); //开启信息窗口
//         //     });
//         // });
//         // var markerClusterer = new BMapLib.MarkerClusterer(map, { markers: markers }).setGridSize(50);
//     }
// });


var dataSet = null;

function showLine(lineStr) {
    var pointArrs = [];
    var data = [];
    var lines = lineStr.split(";");
    for (var j = 0; j < lines.length; j++) {
        var points = lines[j].split(",");
        var pointArr = [];
        var coordinates = [];
        for (var i = 0; i < points.length; i += 2) {
            point = new BMap.Point(points[i], points[i + 1]);
            pointArr.push(point);
            pointArrs.push(point);
            coordinates.push([points[i], points[i + 1]]);
        }
        data.push({
            geometry: {
                type: 'LineString',
                coordinates: coordinates
            },
            count: 1
        });
        // var polyline = new BMap.Polyline(pointArr,{strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5});
        // map.addOverlay(polyline);
    }

    if (!dataSet) {
        dataSet = new mapv.DataSet(data);
        var options = {
            strokeStyle: 'rgba(55, 50, 250, 0.7)',
            shadowColor: 'rgba(55, 50, 250, 0.7)',
            shadowBlur: 10,
            lineWidth: 3,
            draw: 'simple'
        }

        var mapvLayer = new mapv.baiduMapLayer(map, dataSet, options);

    } else {
        dataSet.set(data);
    }

    //map.setViewport(pointArrs);


}


$('#searchBtnPoi').bind('click', function () {
    clearMarkers();

    var options = getOptions('poi');

    $.getJSON(server + 'search?callback=?', options, function (rs) {
        var results = rs.results;
        //console.log(results);
        for (var i = 0; i < results.length; i++) {
            var result = results[i];
            (function (result) {
                var icon = new BMap.Icon("markers.png", new BMap.Size(8, 8), {
                    "anchor": new BMap.Size(4, 4),
                    "imageOffset": new BMap.Size(-108, -233),
                    "infoWindowAnchor": new BMap.Size(4, 0)
                });
                var iconHover = new BMap.Icon("markers.png", new BMap.Size(8, 8), {
                    "anchor": new BMap.Size(4, 4),
                    "imageOffset": new BMap.Size(-108, -243),
                    "infoWindowAnchor": new BMap.Size(4, 0)
                });
                var marker = new BMap.Marker(new BMap.Point(result.location.lng, result.location.lat), {
                    icon: icon
                });
                marker.addEventListener('mouseover', function () {
                    marker.setIcon(iconHover);
                });
                marker.addEventListener('mouseout', function () {
                    marker.setIcon(icon);
                });
                map.addOverlay(marker);
                var opts = {
                    title: result.alias // 信息窗口标题
                }
                var infoWindow = new BMap.InfoWindow("地址：" + result.address, opts);  // 创建信息窗口对象 
                marker.onclick = function () {
                    this.openInfoWindow(infoWindow);
                }
                markers.push(marker);
            })(result);
        }
    });
});


function getOptions(type) {
    var options = {
        page_size: 100,
        output: 'json'
    }
    if (type == 'road') {
        options.q = $("#searchName").val();
        if ($('#roadProvinceSelect').val() != '') {
            options.province = $('#roadProvinceSelect').val();
        }
        if ($('#roadCitySelect').val() != '') {
            options.city = $('#roadCitySelect').val();
        }
    } else if (type == 'poi') {
        options.q = $("#searchNamePoi").val();
        if ($('#poiCity').val() != '') {
            options.city = $('#poiCity').val();
        }
    }

    if (overlays.length > 0) {
        var overlay = overlays[overlays.length-1];
        if (overlay.toString() == '[object Circle]') {
            var center = overlay.getCenter();
            options.location = center.lat + ',' + center.lng;
            options.radius = ~~overlay.getRadius();
        } else if (overlay.toString() == '[object Polygon]') {
            var path = overlay.getPath();
            if (isRect(path)) {
                options.bounds = path[3].lat + ',' + path[3].lng + ',' + path[1].lat + ',' + path[1].lng;
            } else {
                var str = [];
                for (var i = 0; i < path.length; i++) {
                    str.push(path[i].lat + ',' + path[i].lng);
                }
                //console.log(str);
                options.xys = str.join(';');
            }
        }
    }
    return options;
}

function isRect(path) {
    return path.length.length == 4 && path[0].lat == path[1].lat && path[0].lng == path[3].lng && path[1].lng == path[2].lng && path[2].lat == path[3].lat;
}

var markers = [];
function clearMarkers() {
    for (var i = 0; i < markers.length; i++) {
        map.removeOverlay(markers[i]);
    }
    markers.length = 0;
}


//console.log(cityData);
var html = ['<option value="">全国</option>'];

var municipalities = cityData.municipalities;
for (var i = 0; i < municipalities.length; i++) {
    html.push('<option value="' + municipalities[i].n + '市' + '">' + municipalities[i].n + '市' + '</option>');
}

var provinces = cityData.provinces;
for (var i = 0; i < provinces.length; i++) {
    html.push('<option value="' + provinces[i].n + '省' + '">' + provinces[i].n + '省' + '</option>');
}

$('#roadProvinceSelect').html(html.join(''));
$('#zhuangProvince').html(html.join(''));

//console.log(provinces);
$('#roadProvinceSelect').bind('change', function () {
    var province = $(this).val();
    for (var i = 0; i < provinces.length; i++) {
        if (provinces[i].n == province.replace('省', '')) {
            var html = ['<option value="">全省</option>'];
            for (var j = 0; j < provinces[i].cities.length; j++) {
                html.push('<option value="' + provinces[i].cities[j].n + '市' + '">' + provinces[i].cities[j].n + '市' + '</option>');
            }
            $('#roadCitySelect').html(html.join(''));
        }
    }
});

$('#zhuangSearchBtn').bind('click', function () {


    var url = server + "roadpile?callback=?";
    var options = {
        q: $('#zhuangName').val(),
        kpile: $('#kpile').val(),
        mpile: $('#mpile').val(),
        province: $('#zhuangProvince').val(),
        output: 'json'
    }

    $.getJSON(url, options, function (rs) {
        var results = rs.results;
        for (var i = 0; i < results.length; i++) {
            var item = results[i];
            //console.log(item);
            var marker = new BMap.Marker(new BMap.Point(item.location.lng, item.location.lat));
            map.addOverlay(marker);
            (function (item) {
                var opts = {
                    title: item.name, // 信息窗口标题
                }
                var html = "<p>省份:" + item.province + "</p>"
                    + "<p>城市：" + item.city + "</p>"
                    + "<p>地区：" + item.district + "</p>"
                    + "<p>桩米数：" + item.pileNum + "</p>"
                    ;
                var infoWindow = new BMap.InfoWindow(html, opts);  // 创建信息窗口对象 
                marker.addEventListener('click', function () {
                    this.openInfoWindow(infoWindow);
                });
            })(item);
        }
    });
});


var trafficLayer = new BMap.TrafficLayer();

$('#openTraffic').bind('click', function () {
    map.addTileLayer(trafficLayer);
});

$('#closeTraffic').bind('click', function () {
    map.removeTileLayer(trafficLayer);
});
